package com.atguigu.edu.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.app.BaseApp;
import com.atguigu.edu.util.AtguiguUtil;
import com.atguigu.edu.common.Constant;
import com.atguigu.edu.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

public class Dwd_01_DwdBaseLogApp extends BaseApp {
    public static void main(String[] args) {
        new Dwd_01_DwdBaseLogApp().init(
                3001,
                2,
                "Dwd_01_DwdBaseLogApp",
                Constant.TOPIC_ODS_LOG
        );
    }

    private final String START = "start";
    private final String DISPLAY = "display";
    private final String ACTION = "action";
    private final String ERR = "err";
    private final String PAGE = "page";

    @Override
    public void handle(StreamExecutionEnvironment ev, 
                       DataStreamSource<String> stream) {
        //1.etl
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);
        //2. 新老客户标记纠正
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        //3. 分流
        Map<String, DataStream<JSONObject>> streams = splitStream(validatedStream);
        //4. 不同的流写出到不同的 topic 中
        writeToKafka(streams);
    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
                .filter(new FilterFunction<String>() {
                    @Override
                    public boolean filter(String value) throws Exception {
                        try {
                            JSON.parseObject(value);
                            return true;
                        } catch (Exception e) {
                            System.out.println("不是正确的 json 数据: " + value);
                            return false;
                        }
                    }
                })
                .map(JSON::parseObject);
    }

    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> firstVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        firstVisitDateState = getRuntimeContext()
                                .getState(new ValueStateDescriptor<String>("firstVisitDate", String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject obj) throws Exception {
                        Long ts = obj.getLong("ts");

                        String today = AtguiguUtil.tsToDate(ts);

                        JSONObject common = obj.getJSONObject("common");

                        String isNew = common.getString("is_new");

                        String firstVisitDate = firstVisitDateState.value();

                        if ("1".equals(isNew)) {
                            if (firstVisitDate == null) {
                                firstVisitDateState.update(today);
                            }else{
                                //判断今天与状态的日期是否一致
                                if (!today.equals(firstVisitDate)) {
                                    common.put("is_new", "0");
                                }
                            }
                        }else{
                            // 如果状态是 null, 把这个用户的首次访问记录设置为昨天
                            if (firstVisitDate == null) {
                                firstVisitDateState.update(AtguiguUtil.tsToDate(ts - 24 * 60 * 60 * 1000));
                            }
                        }
                        return obj;
                    }
                });
    }

    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> stream) {
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display"){};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page"){};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err"){};
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action"){};

        //主流是启动日志
        SingleOutputStreamOperator<JSONObject> startStream = stream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject obj,
                                       Context ctx,
                                       Collector<JSONObject> out) throws Exception {

                JSONObject common = obj.getJSONObject("common");
                Long ts = obj.getLong("ts");
                //1. 启动日志
                JSONObject start = obj.getJSONObject("start");
                if (start != null) {
                    // 补充一些其他有用字段
                    start.putAll(common);
                    start.put("ts", ts);
                    out.collect(start);
                }
                //2. 曝光日志
                JSONArray displays = obj.getJSONArray("displays");
                if (displays != null) {
                    for (int i = 0; i < displays.size(); i++) {
                        JSONObject display = displays.getJSONObject(i);
                        display.putAll(common);
                        display.put("ts", ts);
                        ctx.output(displayTag, display);
                    }
                }
                //3. 曝光日志
                JSONArray actions = obj.getJSONArray("actions");
                if (actions != null) {
                    for (int i = 0; i < actions.size(); i++) {
                        JSONObject action = actions.getJSONObject(i);
                        action.putAll(common);
                        ctx.output(actionTag, action);
                    }
                }
                //4. 错误日志
                JSONObject err = obj.getJSONObject("err");
                if (err != null) {
                    err.putAll(common);
                    err.put("ts", ts);
                    ctx.output(errTag, err);
                }
                //5. 页面日志
                JSONObject page = obj.getJSONObject("page");
                if (page != null) {
                    page.putAll(common);
                    page.put("ts", ts);
                    ctx.output(pageTag, page);
                }
            }
        });

        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        DataStream<JSONObject> actionStream = startStream.getSideOutput(actionTag);
        DataStream<JSONObject> errStream = startStream.getSideOutput(errTag);
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);

        //分流输出
        Map<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START, startStream);
        streams.put(DISPLAY, displayStream);
        streams.put(ACTION, actionStream);
        streams.put(ERR, errStream);
        streams.put(PAGE, pageStream);
        return streams;

    }

    private void writeToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
    }

}
